package cn.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBUtil {
	// 1、数据库连接参数
	private static String driver;
	private static String url;
	private static String userName;
	private static String passWord;

	// 2、加载驱动，获得连接
	static {
		Properties p = new Properties();
		// 打开流
		InputStream in = DBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
		try {
			p.load(in);
			driver = p.getProperty("driver");
			url = p.getProperty("url");
			userName = p.getProperty("userName");
			passWord = p.getProperty("passWord");
			// 加载驱动
			Class.forName(driver);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 3、获得连接
	public Connection getConnection() {
		try {
			Connection ct = DriverManager.getConnection(url, userName, passWord);
			// 开启事务管理
			ct.setAutoCommit(false);
			// 设置事务隔离级别
			ct.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
			return ct;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		DBUtil u = new DBUtil();
		Connection ct = u.getConnection();
		System.out.println(ct);
	}

	// 4、释放资源
	public void release(Connection ct, Statement ps, ResultSet st) {
		if (st != null) {
			try {
				st.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (ps != null) {
			try {
				ps.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (ct != null) {
			try {
				ct.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// 通用的增删改方法：cud
	public <T> Integer[] cud(Class<T> clazz, String sql, Object... args) {
		Connection ct = getConnection();
		PreparedStatement ps = null;
		ResultSet st = null;
		Integer[] num = new Integer[2];
		System.out.println(sql);
		try {
			ps = ct.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
			for (int i = 0; i < args.length; i++) {
				ps.setObject((i + 1), args[i]);
			}
			// 几条受影响
			int rowNum = ps.executeUpdate();
			// 获得自增长的建
			st = ps.getGeneratedKeys();
			int k = -1;
			if (st.next()) {
				k = st.getInt(1);
			}
			num[0] = rowNum;
			num[1] = k;
			ct.commit();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				ct.rollback();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} finally {
			release(ct, ps, st);
		}
		return num;
	}
}
